<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询 | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="在企业开发中ORM框架有很多种如：Hibernate，Mybatis，JdbcTemplate等。每一种框架的设计理念是不一样的，Hibernate跟我们本章讲解的SpringDataJPA是一致的框架都是全自动理念作为设计核心，让用户更少的去写SQL语句通过简单的配置就可以实现各种查询。而Mybatis框架则是半自动理念作为设计核心，SQL让用户自己定义实现了更好的灵活性。">
<meta name="keywords" content="SpringBoot,QueryDSL">
<meta property="og:type" content="article">
<meta property="og:title" content="第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询">
<meta property="og:url" content="http://blog.yuqiyu.com/querydsl-chapter-2/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="在企业开发中ORM框架有很多种如：Hibernate，Mybatis，JdbcTemplate等。每一种框架的设计理念是不一样的，Hibernate跟我们本章讲解的SpringDataJPA是一致的框架都是全自动理念作为设计核心，让用户更少的去写SQL语句通过简单的配置就可以实现各种查询。而Mybatis框架则是半自动理念作为设计核心，SQL让用户自己定义实现了更好的灵活性。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-a1687058dc9c36da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-88ee0737eb15a7ac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-40214aef75dd839e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-4b49a0880aa7bd8a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-581c287d1ca7ca78.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-01-23T16:08:31.007Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询">
<meta name="twitter:description" content="在企业开发中ORM框架有很多种如：Hibernate，Mybatis，JdbcTemplate等。每一种框架的设计理念是不一样的，Hibernate跟我们本章讲解的SpringDataJPA是一致的框架都是全自动理念作为设计核心，让用户更少的去写SQL语句通过简单的配置就可以实现各种查询。而Mybatis框架则是半自动理念作为设计核心，SQL让用户自己定义实现了更好的灵活性。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-a1687058dc9c36da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-querydsl-chapter-2" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/querydsl-chapter-2/">
            <time datetime="2017-07-01T16:00:00.000Z" itemprop="datePublished">2017-07-02</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/QueryDSL/">QueryDSL</a>, <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>在企业开发中ORM框架有很多种如：Hibernate，Mybatis，JdbcTemplate等。每一种框架的设计理念是不一样的，Hibernate跟我们本章讲解的SpringDataJPA是一致的框架都是全自动理念作为设计核心，让用户更少的去写SQL语句通过简单的配置就可以实现各种查询。而Mybatis框架则是半自动理念作为设计核心，SQL让用户自己定义实现了更好的灵活性。<br><a id="more"></a></p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>本章我们目标实现QueryDSL通用查询语言整合SpringDataJPA完成单表的查询多样化。</p>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>下面我们先来创建一个SpringBoot项目，具体如何使用Maven整合QueryDSL请访问<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL学习目录第一章</a>，创建项目时的依赖也与第一章一致，pom.xml配置文件如下代码块所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;</span><br><span class="line">    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;</span><br><span class="line"></span><br><span class="line">    &lt;groupId&gt;com.yuqiyu.querydsl.sample&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;chapter2&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;</span><br><span class="line">    &lt;packaging&gt;war&lt;/packaging&gt;</span><br><span class="line"></span><br><span class="line">    &lt;name&gt;chapter2&lt;/name&gt;</span><br><span class="line">    &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;</span><br><span class="line"></span><br><span class="line">    &lt;parent&gt;</span><br><span class="line">        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;1.5.4.RELEASE&lt;/version&gt;</span><br><span class="line">        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;</span><br><span class="line">    &lt;/parent&gt;</span><br><span class="line"></span><br><span class="line">    &lt;properties&gt;</span><br><span class="line">        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;</span><br><span class="line">        &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;</span><br><span class="line">        &lt;java.version&gt;1.8&lt;/java.version&gt;</span><br><span class="line">    &lt;/properties&gt;</span><br><span class="line"></span><br><span class="line">    &lt;dependencies&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line"></span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">            &lt;scope&gt;runtime&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--阿里巴巴数据库连接池，专为监控而生 --&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;druid&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.0.26&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!-- 阿里巴巴fastjson，解析json视图 --&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;fastjson&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.2.15&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;</span><br><span class="line">            &lt;!--&lt;scope&gt;provided&lt;/scope&gt;--&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;</span><br><span class="line">            &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--queryDSL--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.querydsl&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;querydsl-jpa&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;$&#123;querydsl.version&#125;&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.querydsl&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;querydsl-apt&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;$&#123;querydsl.version&#125;&lt;/version&gt;</span><br><span class="line">            &lt;scope&gt;provided&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;lombok&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.16.16&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br><span class="line"></span><br><span class="line">    &lt;build&gt;</span><br><span class="line">        &lt;plugins&gt;</span><br><span class="line">            &lt;plugin&gt;</span><br><span class="line">                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;</span><br><span class="line">            &lt;/plugin&gt;</span><br><span class="line">            &lt;!--添加QueryDSL插件支持--&gt;</span><br><span class="line">            &lt;plugin&gt;</span><br><span class="line">                &lt;groupId&gt;com.mysema.maven&lt;/groupId&gt;</span><br><span class="line">                &lt;artifactId&gt;apt-maven-plugin&lt;/artifactId&gt;</span><br><span class="line">                &lt;version&gt;1.1.3&lt;/version&gt;</span><br><span class="line">                &lt;executions&gt;</span><br><span class="line">                    &lt;execution&gt;</span><br><span class="line">                        &lt;goals&gt;</span><br><span class="line">                            &lt;goal&gt;process&lt;/goal&gt;</span><br><span class="line">                        &lt;/goals&gt;</span><br><span class="line">                        &lt;configuration&gt;</span><br><span class="line">                            &lt;outputDirectory&gt;target/generated-sources/java&lt;/outputDirectory&gt;</span><br><span class="line">                            &lt;processor&gt;com.querydsl.apt.jpa.JPAAnnotationProcessor&lt;/processor&gt;</span><br><span class="line">                        &lt;/configuration&gt;</span><br><span class="line">                    &lt;/execution&gt;</span><br><span class="line">                &lt;/executions&gt;</span><br><span class="line">            &lt;/plugin&gt;</span><br><span class="line">        &lt;/plugins&gt;</span><br><span class="line">    &lt;/build&gt;</span><br><span class="line">&lt;/project&gt;</span><br></pre></td></tr></table></figure></p>
<p>上图代码块有关配置如有不明白的地方请查看<a href="http://www.jianshu.com/p/a22447c0897c" target="_blank" rel="noopener">第一章：Maven环境下如何配置QueryDSL环境</a>。</p>
<h1 id="构建数据库信息表"><a href="#构建数据库信息表" class="headerlink" title="构建数据库信息表"></a>构建数据库信息表</h1><p>我们先来创建一张普通信息表，创建表SQL如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">DROP TABLE IF EXISTS `t_user`;</span><br><span class="line">CREATE TABLE `t_user` (</span><br><span class="line">  `t_id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;编号&apos;,</span><br><span class="line">  `t_name` varchar(30) DEFAULT NULL COMMENT &apos;名称&apos;,</span><br><span class="line">  `t_age` int(10) DEFAULT NULL COMMENT &apos;年龄&apos;,</span><br><span class="line">  `t_address` varchar(100) DEFAULT NULL COMMENT &apos;家庭住址&apos;,</span><br><span class="line">  `t_pwd` varchar(100) CHARACTER SET latin1 DEFAULT NULL COMMENT &apos;用户登录密码&apos;,</span><br><span class="line">  PRIMARY KEY (`t_id`)</span><br><span class="line">) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;</span><br></pre></td></tr></table></figure></p>
<p>测试数据这里就不添加了。</p>
<h2 id="添加application-yml配置文件"><a href="#添加application-yml配置文件" class="headerlink" title="添加application.yml配置文件"></a>添加application.yml配置文件</h2><p>在resource目录下我们添加application.yml配置文件来代替application.properties文件，添加对应的数据库连接池的配置信息，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  datasource:</span><br><span class="line">      type: com.alibaba.druid.pool.DruidDataSource</span><br><span class="line">      url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8</span><br><span class="line">      username: root</span><br><span class="line">      password: root</span><br><span class="line">      driver-class-name: com.mysql.jdbc.Driver</span><br><span class="line">      filters: stat</span><br><span class="line">      maxActive: 20</span><br><span class="line">      initialSize: 1</span><br><span class="line">      maxWait: 60000</span><br><span class="line">      minIdle: 1</span><br><span class="line">      timeBetweenEvictionRunsMillis: 60000</span><br><span class="line">      minEvictableIdleTimeMillis: 300000</span><br><span class="line">      validationQuery: select &apos;x&apos;</span><br><span class="line">      testWhileIdle: true</span><br><span class="line">      testOnBorrow: false</span><br><span class="line">      testOnReturn: false</span><br><span class="line">      poolPreparedStatements: true</span><br><span class="line">      maxOpenPreparedStatements: 20</span><br><span class="line">  jpa:</span><br><span class="line">    properties:</span><br><span class="line">      hibernate:</span><br><span class="line">        show_sql: true</span><br><span class="line">        format_sql: true</span><br></pre></td></tr></table></figure></p>
<h2 id="创建实体"><a href="#创建实体" class="headerlink" title="创建实体"></a>创建实体</h2><p>我们根据数据库内对应的字段创建一个实体类并添加对应的SpringDataJPA的注解，实体类代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter2.bean;</span><br><span class="line">import lombok.Data;</span><br><span class="line">import javax.persistence.*;</span><br><span class="line">import java.io.Serializable;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/2</span><br><span class="line"> * Time：18:31</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;t_user&quot;)</span><br><span class="line">public class UserBean implements Serializable</span><br><span class="line">&#123;</span><br><span class="line">    @Id</span><br><span class="line">    @Column(name = &quot;t_id&quot;)</span><br><span class="line">    @GeneratedValue</span><br><span class="line">    private Long id;</span><br><span class="line">    @Column(name = &quot;t_name&quot;)</span><br><span class="line">    private String name;</span><br><span class="line">    @Column(name = &quot;t_age&quot;)</span><br><span class="line">    private int age;</span><br><span class="line">    @Column(name = &quot;t_address&quot;)</span><br><span class="line">    private String address;</span><br><span class="line">    @Column(name = &quot;t_pwd&quot;)</span><br><span class="line">    private String pwd;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>实体内有个注解@Data比较特殊，之前也许大家没有使用过，当然你们肯定发现了我这个实体类内并没有对应字段的Getter/Setter方法，如果没有添加@Data注解在SpringDataJPA映射数据时会出现找不到对应字段的Setter方法，导致无法完成数据映射到实体的异常！<br>在上面的实体源码中可以看到@Data注解是在lombok包内，lombok其实是一个优雅的第三方插件，它可以让你的实体变得简洁，可读性也大大的得到了提升。在使用这个插件的时候需要你们Idea开发工具支持，必填安装相应的Plugin才可以，这里我就不多说相关lombok的配置问题了，大家在跟本章联系的时候可以使用Getter/Setter方法的形式代替@Data。</p>
<h2 id="创建基类JPA"><a href="#创建基类JPA" class="headerlink" title="创建基类JPA"></a>创建基类JPA</h2><p>这里我们简单的封装下JPA，我们添加一个接口去继承我们需要的JPA接口并让所有子类继承我们的基类接口就可以了，基类JPA代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter2.jpa;</span><br><span class="line">import org.springframework.data.jpa.repository.JpaRepository;</span><br><span class="line">import org.springframework.data.jpa.repository.JpaSpecificationExecutor;</span><br><span class="line">import org.springframework.data.querydsl.QueryDslPredicateExecutor;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 核心JPA</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/2</span><br><span class="line"> * Time：18:23</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@NoRepositoryBean</span><br><span class="line">public interface BaseJPA&lt;T&gt;</span><br><span class="line">        extends JpaRepository&lt;T,Long&gt;,</span><br><span class="line">        JpaSpecificationExecutor&lt;T&gt;,</span><br><span class="line">        QueryDslPredicateExecutor&lt;T&gt;</span><br><span class="line">&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的注解@NoRepositoryBean是为了避免SpringDataJPA自动实例化才添加的。</p>
<h2 id="创建逻辑JPA"><a href="#创建逻辑JPA" class="headerlink" title="创建逻辑JPA"></a>创建逻辑JPA</h2><p>接下来我们开始创建对应User模块的数据逻辑接口JPA，很简单，我们只需要创建一个接口继承下我们的BaseJPA就可以了，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter2.jpa;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter2.bean.UserBean;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/2</span><br><span class="line"> * Time：18:39</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">public interface UserJPA</span><br><span class="line">        extends BaseJPA&lt;UserBean&gt;</span><br><span class="line">&#123;</span><br><span class="line">  //../可以添加命名方法查询</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们在继承BaseJPA的时候用到了泛型，因为我们在BaseJPA内所继承的接口都需要我们传递一个具体的实体类的类型，所以这块我们采用了泛型来处理，只有具体逻辑JPA继承BaseJPA的时候传递具体的实体类型就可以了。</p>
<h2 id="自动生成Q结构查询实体"><a href="#自动生成Q结构查询实体" class="headerlink" title="自动生成Q结构查询实体"></a>自动生成Q结构查询实体</h2><p>我们之前说过了QueryDSL很神奇的地方就在于它是一个可通过Maven插件自动生成实体类型的结构查询实体，那么我们接下来使用maven compile命令来让我们配置的JPAAnnotationProcessor去做他自己的使命。<br>idea工具为我们的maven项目自带了比较全面的命令，我们直接使用就可以了，如下图1所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-a1687058dc9c36da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1"><br>双击红色框内的命令就可以执行了，在这之前如果你想使用本地的maven环境需要在Setting-&gt;Build Tools -&gt;maven页面修改home dirctory。命令执行完成后我们可以看到target目录自动生成了并且为我们创建了一些目录，展开目录后可以看到QueryDSL为我们自动生成的查询实体，如下图2所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-88ee0737eb15a7ac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2"><br>maven插件会为我们自动创建一堆目录，我们的查询实体的位置是以我们pom.xml配置文件内配置的目录为准。打开自动创建的实体后可以看到QueryDSL自动为我们创建的查询字段以及构造函数，具体查询字段的含义后面会有所讲解。</p>
<h1 id="编写查询"><a href="#编写查询" class="headerlink" title="编写查询"></a>编写查询</h1><p>下面我们开始编写查询，在编写之前我们创建一个控制器用于查看我们查询到的数据，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter2.controller;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter2.jpa.UserJPA;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line">import org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/2</span><br><span class="line"> * Time：18:38</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@RestController</span><br><span class="line">@RequestMapping(value = &quot;/user&quot;)</span><br><span class="line">public class UserController</span><br><span class="line">&#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UserJPA userJPA;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里我并没有追寻MVC三层的设计理念，因为这只是文章的测试Sample编写，大家在实际开发项目中还是需要按照MVC设计模式来进行设计架构。</p>
<h3 id="查询全部数据并排序"><a href="#查询全部数据并排序" class="headerlink" title="查询全部数据并排序"></a>查询全部数据并排序</h3><p>我们先来一个简单的查询表内的所有数据并根据主键进行倒序，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">@RequestMapping(value = &quot;/user&quot;)</span><br><span class="line">public class UserController</span><br><span class="line">&#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UserJPA usrJPA;</span><br><span class="line"></span><br><span class="line">    //----以下是新添加内容</span><br><span class="line"></span><br><span class="line">    //实体管理者</span><br><span class="line">    @Autowired</span><br><span class="line">    private EntityManager entityManager;</span><br><span class="line"></span><br><span class="line">    //JPA查询工厂</span><br><span class="line">    private JPAQueryFactory queryFactory;</span><br><span class="line"></span><br><span class="line">    @PostConstruct</span><br><span class="line">    public void initFactory()</span><br><span class="line">    &#123;</span><br><span class="line">        queryFactory = new JPAQueryFactory(entityManager);</span><br><span class="line">        System.out.println(&quot;init JPAQueryFactory successfully&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 查询全部数据并根据id倒序</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @RequestMapping(value = &quot;/queryAll&quot;)</span><br><span class="line">    public List&lt;UserBean&gt; queryAll()</span><br><span class="line">    &#123;</span><br><span class="line">        //使用querydsl查询</span><br><span class="line">        QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line">        //查询并返回结果集</span><br><span class="line">        return queryFactory</span><br><span class="line">                .selectFrom(_Q_user)//查询源</span><br><span class="line">                .orderBy(_Q_user.id.desc())//根据id倒序</span><br><span class="line">                .fetch();//执行查询并获取结果集</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>在使用QueryDSL进行查询之前我们声明了EntityManager的注入以及JPAQueryFactory工厂对象的创建，通过@PostConstruct注解在类初始化的时候完成对JPAQueryFactory对象的实例化。</p>
<p>我们在queryAll方法内首先获取了对应UserBean的查询实体QUserBean，通过QUserBean内自动生成的字段获取，我们使用JPAQueryFactory工厂对象的selectFrom方法来简化查询，该方法代替了select&amp;from两个方法，注意：也是仅限单表操作时可以使用。</p>
<p>而我们倒序的方式看起来就更简单了，这种实现方式完全就像是在编写原始的SQL一样，如果是根据asc的方式进行排序则可以修改为： orderBy(_Q_user.id.asc())，看起来是不是特别简单？</p>
<p>在一系列的条件都添加完成后，调用fetch方法执行我们的条件查询并且获取对应selectFrom查询实体的类型集合，要注意一点：这里如果selectFrom参数的实体类型不是UserBean那fetch方法返回集合的类型也不是List<userbean>。</userbean></p>
<blockquote>
<p>注意：在我们启动项目之前，我们需要修改pom.xml配置文件添加相关inject的依赖，SpringBoot内部并没有为我们提供该依赖。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;javax.inject&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;javax.inject&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>添加该依赖后才能完成JPAQueryFactory的实例化，下面我们启动下项目访问地址看界面输出内容如下图3所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-40214aef75dd839e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3"></p>
<p>可以看到上图3的输出内容数据是完全按照我们的查询条件来执行的，我们打开控制台看看SpringDataJPA为我们自动生成的SQL<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        userbean0_.t_id as t_id1_0_,</span><br><span class="line">        userbean0_.t_address as t_addres2_0_,</span><br><span class="line">        userbean0_.t_age as t_age3_0_,</span><br><span class="line">        userbean0_.t_name as t_name4_0_,</span><br><span class="line">        userbean0_.t_pwd as t_pwd5_0_ </span><br><span class="line">    from</span><br><span class="line">        t_user userbean0_ </span><br><span class="line">    order by</span><br><span class="line">        userbean0_.t_id desc</span><br></pre></td></tr></table></figure></p>
<p>可以看到在SQL上面输出了Hibernate，StringDataJPA生成SQL这一块是使用的Hibernate，所以我们可以完全使用HQL的查询语言来编写JPA的查询。</p>
<h3 id="根据主键查询单条数据"><a href="#根据主键查询单条数据" class="headerlink" title="根据主键查询单条数据"></a>根据主键查询单条数据</h3><p>查询详情方法是我们常用到的查询之一，一般用于删除、更新。下面我们就来编写一个detail方法来看来QueryDSL是如何完成查询单挑数据的。</p>
<h4 id="完全QueryDSL风格"><a href="#完全QueryDSL风格" class="headerlink" title="完全QueryDSL风格"></a>完全QueryDSL风格</h4><p>代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 查询详情</span><br><span class="line">    * @param id 主键编号</span><br><span class="line">    * @return</span><br><span class="line">    */</span><br><span class="line">   @RequestMapping(value = &quot;/detail/&#123;id&#125;&quot;)</span><br><span class="line">   public UserBean detail(@PathVariable(&quot;id&quot;) Long id)</span><br><span class="line">   &#123;</span><br><span class="line">       //使用querydsl查询</span><br><span class="line">       QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line">       //查询并返回结果集</span><br><span class="line">       return queryFactory</span><br><span class="line">               .selectFrom(_Q_user)//查询源</span><br><span class="line">               .where(_Q_user.id.eq(id))//指定查询具体id的数据</span><br><span class="line">               .fetchOne();//执行查询并返回单个结果</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="SpringDataJPA整合QueryDSL风格"><a href="#SpringDataJPA整合QueryDSL风格" class="headerlink" title="SpringDataJPA整合QueryDSL风格"></a>SpringDataJPA整合QueryDSL风格</h4><p>代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * SpringDataJPA &amp; QueryDSL实现单数据查询</span><br><span class="line"> * @param id</span><br><span class="line"> * @return</span><br><span class="line"> */</span><br><span class="line">@RequestMapping(value = &quot;/detail_2/&#123;id&#125;&quot;)</span><br><span class="line">public UserBean detail_2(@PathVariable(&quot;id&quot;) Long id)</span><br><span class="line">&#123;</span><br><span class="line">    //使用querydsl查询</span><br><span class="line">    QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line">    //查询并返回指定id的单条数据</span><br><span class="line">    return userJPA.findOne(_Q_user.id.eq(id));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的两种风格都是可以根据id字段返回指定的单条数据，当然在上面的编写看来还是使用SpringDataJPA &amp; QueryDSL要简单些，也只是简单的查询整合风格要比纯QueryDSL要简便，但是如果添加排序、模糊查询时还是纯QueryDSL编写更简单一些。</p>
<p>查询指定主键时，我们使用了where方法并且指定了id字段需要eq参数id，这个eq是QueryDSL内置的一个方法，用于查询指定值数据，当然其他字段也同样可以使用eq方法来完成条件查询，都是可以变通使用的。</p>
<p>重启项目后我们来看下查询详情的运行效果，如下图4所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-4b49a0880aa7bd8a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4"></p>
<p>我们再来看下控制台输出的生成SQL，如下代码所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        userbean0_.t_id as t_id1_0_,</span><br><span class="line">        userbean0_.t_address as t_addres2_0_,</span><br><span class="line">        userbean0_.t_age as t_age3_0_,</span><br><span class="line">        userbean0_.t_name as t_name4_0_,</span><br><span class="line">        userbean0_.t_pwd as t_pwd5_0_ </span><br><span class="line">    from</span><br><span class="line">        t_user userbean0_ </span><br><span class="line">    where</span><br><span class="line">        userbean0_.t_id=?</span><br></pre></td></tr></table></figure></p>
<p>可以看到是根据我们指定的字段来作为查询条件来检索的数据，我们通过fetchOne方法来返回一个结果。</p>
<h3 id="根据名称模糊查询"><a href="#根据名称模糊查询" class="headerlink" title="根据名称模糊查询"></a>根据名称模糊查询</h3><p>下面我们来根据字段name完成模块查询，先来看下我们的查询条件代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * 根据名称模糊查询</span><br><span class="line">     * @param name</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @RequestMapping(value = &quot;/likeQueryWithName&quot;)</span><br><span class="line">    public List&lt;UserBean&gt; likeQueryWithName(String name)</span><br><span class="line">    &#123;</span><br><span class="line">        //使用querydsl查询</span><br><span class="line">        QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line"></span><br><span class="line">        return queryFactory</span><br><span class="line">                .selectFrom(_Q_user)//查询源</span><br><span class="line">                .where(_Q_user.name.like(name))//根据name模糊查询</span><br><span class="line">                .fetch();//执行查询并返回结果集</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看到我们where条件是根据name字段的like方法来完成的模糊查询，like方法也是QueryDSL内置的方法，我们只需要传入查询的内容就可以实现模糊查询，下面我们来运行访问看下界面输出内容如下图5所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-581c287d1ca7ca78.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5"><br>我们可以看到仅输出了name跟我们传入’admin’相关的数据，那我们看下控制台是怎么给我们生成的SQL：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        userbean0_.t_id as t_id1_0_,</span><br><span class="line">        userbean0_.t_address as t_addres2_0_,</span><br><span class="line">        userbean0_.t_age as t_age3_0_,</span><br><span class="line">        userbean0_.t_name as t_name4_0_,</span><br><span class="line">        userbean0_.t_pwd as t_pwd5_0_ </span><br><span class="line">    from</span><br><span class="line">        t_user userbean0_ </span><br><span class="line">    where</span><br><span class="line">        userbean0_.t_name like ? escape &apos;!&apos;</span><br></pre></td></tr></table></figure></p>
<p>也是完全按照我们指定的模糊查询字段生成的，到目前可以看到QueryDSL为我们减少了太多了查询繁琐的事情，让我们能够更好的投入到业务逻辑处理中。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>以上内容就是本章的全部讲解，本章主要讲述了SpringDataJPA整合QueryDSL后完全使用QueryDSL来进行单表的查询，使用QueryDSL可以完全按照编写原始SQL的思想来编写查询条件，容易上手，方便快捷。由于QueryDSL的功能强大，有很多东西没有讲解到，希望大家可以在后期的项目中得到总结。</p>
<p>本章源码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a><br>感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/querydsl-chapter-3/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete
                
            </div>
        </a>
    
    
        <a href="/querydsl-chapter-1/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第一章：Maven环境下如何配置QueryDSL环境</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>